var {
  http
} = require('../../utils/apiutils');
let ctx = null; //Camera
const qiniu = require("../../utils/qnutils");

Page({

  /**
   * 页面的初始数据
   */
  data: {
    activeNames: ['1'],
    id: "",
    dataList: [],
    renz: false,
    info: {},
    speed: 0,
    secondList: [],
  },
  onChange(event) {
    this.setData({
      activeNames: event.detail,
    });
  },
  takePhoto() {
    console.log("--------生成照片-------")
    ctx = wx.createCameraContext(); //初始化camera
    ctx.takePhoto({ //生成图片
      quality: 'high',
      success: (res) => { //得到图片
        this.setData({
          baseImg: res.tempImagePath,
          isSuccess: true,
        })
      }
    })
  },
  clearPhoto: function () {
    this.setData({
      baseImg: "",
      isSuccess: false,
    })
  },

  confirmBack: function () {
    this.getUpToken(this.data.baseImg);
  },
  getUpToken: function (url) {
    var that = this;
    http.getUpToken({},
      function (res) {
        // console.log("----七牛云的授权码---", res);
        qiniu.initQiniu(res.data);
        that.upDataImage(url);
      },
      function (err) {

      })
  },
  upDataImage: function (tempFilePaths) {
    var that = this;
    qiniu.getUploadImgae(tempFilePaths,
      function (res) {
        var data = {
          url: res.key,
          trainingId: that.data.id,
          groupId: that.data.cData.id,
        }
        that.faceAuth(data)
      },
      function (err) { })
  },
  faceAuth: function (data) {
    var that = this;
    console.log("-----头像链接---------", data);
    http.faceAuth(data,
      function (res) {
        if (res.status == 200) {
          wx.showToast({
            title: '认证成功',
            icon: "none",
          })

          that.pushVodeo();
        } else {
          wx.showToast({
            title: res.message,
            icon: "none",
          })
          that.clearPhoto();
        }

      },
      function (err) {

      })

  },
  getTrainDirectory: function () {
    var data = {
      trainId: this.data.id,
    }
    var that = this;
    wx.showLoading({
      title: '加载中...',
    })
    http.getTrainDirectory(data,
      function (res) {
        wx.hideLoading()
        console.log("---返回数据------", res);
        if (res.status == 200) {
          // // 按照课程序号对数据排序
          // var courseList=res.data

          // courseList.map(item=>{
          //   var sortArr=[];
          //   var str,regNum,num;
          //   item.directoryVoList.map((ite,index)=>{
          //     str=ite.directoryName.trim()
          //     regNum=str.search(/[.]/)
          //     if(regNum>0){
          //       num=str.substring(0,regNum)
          //       sortArr[num-1]=item.directoryVoList[index]
          //     }else{
          //       sortArr.push(item.directoryVoList[index])
          //     }     
          //   })

          //   item.directoryVoList=sortArr

          // })

          that.setData({
            dataList: res.data,
            // dataList: courseList,
          })

          that.data.dataList.map((item) => {
            item.directoryVoList.map((ite, index) => {
              that.data.secondList.push({ name: ite.directoryName, finish: ite.finish })
            })
          })



        } else {
          wx.showToast({
            title: res.message,
            icon: "none",
          })
        }
      },
      function (err) {
        wx.hideLoading()
      })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var {
      id,
      name,
      speed,
      passType,
      faceIdentification,
      popup
    } = options
    wx.getSystemInfo({
      success: res => {
        this.setData({
          info: res,
        })
      }
    })
    wx.setNavigationBarTitle({
      title: name,
    })
    this.setData({
      id: id,
      passType: passType,
      speed: speed,
      faceIdentification: faceIdentification,
      popup
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    // if (this.data.id != "") {
    //   this.getTrainDirectory()
    // }

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

    if (this.data.id != "") {
      this.getTrainDirectory();
    }
    this.clearPhoto()

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
    this.data.secondList = []

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    this.data.secondList = []

  },
  onClickVideo(e){
    if(this.data.passType==1){
      this.clickAnswer(e)
    }else if(this.data.passType==2){
      this.clickVideo(e)
    }
  },
  clickVideo: function (e) {
    console.log('拿到的', e)
    var item = e.currentTarget.dataset.item;
    var finish = e.currentTarget.dataset.finish;
    // var courseName=e.currentTarget.dataset.item.directoryName;
    var trainParam = { trainId: this.data.id }
    var that = this
    http.getLastTrainDirectory(trainParam, function (res) {
      var visitTrain = res.data[0]
      console.log('返回：：', visitTrain)
      if (!visitTrain || visitTrain && item.id == visitTrain.directoryVoList[0].id || item.finish == 1) {
        that.setData({
          cData: item,
        })
        // this.pushVodeo()
        // return;
        console.log("-----视频得id----", item, that.data.id, that.data.faceIdentification);
        if (that.data.faceIdentification == 1) {
          let u = getApp().globalData.userInfo;
          if (finish == 1) {
            that.pushVodeo(0, 0)
            return;
          }
          if (!(u.image && u.image != "")) {
            wx.showModal({
              title: '提示',
              content: "该视频需要认证，您尚未上传证件照，无法认证，是否去上传证件照",
              cancelText: "稍后上传",
              confirmText: "去上传",
              success(res) {
                if (res.confirm) {
                  wx.switchTab({
                    url: '/pages/me/me',
                  })
                }
              }
            })
            return;
          }
          // this.pushVodeo(this.data.faceIdentification);
          // return;
          wx.setNavigationBarTitle({
            title: '身份认证',
          })
          that.setData({
            renz: true,
          })
        } else {
          that.pushVodeo(that.data.faceIdentification, that.data.popup)
        }
      } else {
        wx.showToast({
          icon: 'none',
          title: '请学习' + visitTrain.directoryName + '的第' + visitTrain.directoryVoList[0].serialNumber + '节',
          duration: 2000
        })
        return false
      }
    }, function (err) {
      console.log(err)
    })


  },
  clickAnswer: function (e) {
    var item = e.currentTarget.dataset.item;
    var finish = e.currentTarget.dataset.finish;
    this.setData({
      cData: item,
    })
    // this.pushVodeo()
    // return;
    console.log("-----视频得id----", item, this.data.id, this.data.faceIdentification);
    if (this.data.faceIdentification == 1) {
      let u = getApp().globalData.userInfo;
      if (finish == 1) {
        this.pushVodeo(0,0)
        return;
      }
      if (!(u.image && u.image != "")) {
        wx.showModal({
          title: '提示',
          content: "该视频需要认证，您尚未上传证件照，无法认证，是否去上传证件照",
          cancelText: "稍后上传",
          confirmText: "去上传",
          success(res) {
            if (res.confirm) {
              wx.switchTab({
                url: '/pages/me/me',
              })
            }
          }
        })
        return;
      }
      // this.pushVodeo(this.data.faceIdentification);
      // return;
      wx.setNavigationBarTitle({
        title: '身份认证',
      })
      this.setData({
        renz: true,
      })
    } else {
      this.pushVodeo(this.data.faceIdentification,this.data.popup)
    }
  },
  pushVodeo: function (faceIdentification, popup) {

    var item = this.data.cData;
    var that = this;
    wx.navigateTo({
      url: '/pages/student/student?groupId=' + item.id + '&trainingId=' + this.data.id + "&passType=" + this.data.passType + "&name=" + item.directoryName + "&speed=" + this.data.speed + "&faceIdentification=" + faceIdentification + "&popup=" + popup,
      success: (result) => {
        that.setData({
          renz: false,
          success: false,
          baseImg: "",
        })
      },
      fail: (res) => { },
      complete: (res) => { },
    })
  },
  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

})